"use script";

const Sequelize = require("sequelize");

module.exports = (app) => {
  const { STRING, INTEGER, DATE, ENUM } = Sequelize;
  const UsersModel = app.model.define("users", {
    id: {
      type: INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: "用户唯一标识符",
    },
    account: {
      allowNull: false,
      type: STRING(30),
      comment: "用户账号，最大长度为30个字符",
      unique: true,
    },
    password: {
      allowNull: false,
      type: STRING(100),
      comment: "用户密码，最大长度为100个字符",
    },
    roleId: {
      type: INTEGER,
      comment: "用户角色id",
      field: "role_id",
      references: {
        model: app.model.RoleModel,
        key: "id",
        as: "role",
        onDelete: "CASCADE",
      },
    },
    gender: {
      type: ENUM,
      values: ["male", "female", "other"],
      allowNull: false,
      comment: "用户性别，可选值为 male, female, other",
    },
    name: {
      allowNull: false,
      type: STRING(30),
      comment: "用户姓名，最大长度为30个字符",
    },
    age: {
      type: INTEGER,
      comment: "用户年龄",
    },
    phone: {
      type: STRING(20),
      comment: "用户手机号，最大长度为11个字符",
    },
    address: {
      type: STRING(255),
      comment: "用户地址，最大长度为255个字符",
    },
    isShow: {
      field: "is_show",
      type: INTEGER,
      defaultValue: 1,
      comment: "用户是否显示，1为显示，0为隐藏",
    },
    createdAt: {
      field: "created_at",
      type: DATE,
      comment: "创建时间",
    },
    updatedAt: {
      field: "updated_at",
      type: DATE,
      comment: "更新时间",
    },
  });

  UsersModel.prototype.toJSON = function () {
    const data = {
      id: this.id,
      account: this.account,
      password: this.password,
      roleId: this.roleId,
      gender: this.gender,
      name: this.name,
      age: this.age,
      phone: this.phone,
      address: this.address,
      isShow: this.isShow,
      createdAt: this.createdAt,
    };

    if (this.role) data.roleName = this.role.toJSON().roleName;

    return data;
  };

  UsersModel.associate = function () {
    UsersModel.belongsTo(app.model.RoleModel, {
      foreignKey: "role_id",
      as: "role",
      onDelete: "CASCADE",
    });

    // UsersModel.belongsToMany(app.model.RoleModel, {
    //   through: "users_role",
    //   foreignKey: "user_id",
    //   otherKey: "role_id",
    //   as: "role",
    // });

    UsersModel.hasMany(app.model.NoticeModel, {
      foreignKey: "user_id",
      as: "notice",
    });

    UsersModel.hasMany(app.model.ChatModel, {
      foreignKey: "from",
      as: "sentChats",
    });

    UsersModel.hasMany(app.model.ChatModel, {
      foreignKey: "to",
      as: "receivedChats",
    });
  };

  return UsersModel;
};
